import random

from requests import Request, Session
from requests.exceptions import MissingSchema


class Requester:

    def __enter__(self):
        self.session = Session()

        return self

    def execute(self, method, url, headers=None, data=None, params=None, json=None):
        req = Request(method=method, url=url, headers=headers, data=data, params=params, json=json)
        try:
            prepped = self.session.prepare_request(req)
        except Exception as e:
            return str(e), '请求未发送，请求信息报错'
        try:
            resp = self.session.send(prepped, stream=True)
        except Exception as e:

            resp = str(e)
        return prepped, resp

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.session.close()
